import random
import re
import time
import requests
from feishu_bitable_v2 import upload_media, download_image, batch_create_records, get_records_goods_no_list

SHOP_ID = 228447671

cookies = {
    'bos.h5.session': 's%3ApQVm8PUxH4kpNxKcuQitHRcNbnbdBrBq.1R1RNlww9QY5xH6PTilW%2FV0Jz74Ysqa4MKIzf%2BUcZ0o',
    'rprm_cuid_time': str(int(time.time() * 1000)),
    'rprm_cuid': '456304613kmlc0ci0a4g',
    'rprm_uuid': '456304613kmlc0ci0a4g',
    'rprm_appShowId2': '-mab7cnecywy5e718ei',
    'rprm_session_id': ''
}

# 春夏新品-全部
json_data = {
    "refer": "ec-goods-list",
    "extendParameter": {
        "sceneId": "",
        "sceneType": "",
        "tsoTicket": "",
        "wmkTicket": ""
    },
    "basicInfo": {
        "vid": 6001545981671,
        "vidType": 2,
        "bosId": 4001924227671,
        "productId": 145,
        "productInstanceId": 3273861671,
        "productVersionId": "12010",
        "merchantId": 2000019450671,
        "cid": SHOP_ID,
        "tcode": "weimob"
    },
    "extendInfo": {
        "source": 2,
        "youshu": {
            "token": "tokenStr",
            "enable": True
        },
        "refer": "ec-goods-list",
        "deviceInfo": {
            "osType": 2
        },
        "channelsource": 5
    },
    "templateId": 23,
    "queryParameter": {
        "goodsClassifyId": 15004572757671,
        "goodsClassifyName": "全部",
        "search": "",
        "sortBySearch": 1,
        "sortByRule": 2,
        "propSearchInfoList": [],
        "minSalePrice": "",
        "maxSalePrice": "",
        "brandId": "",
        "latitude": "",
        "longitude": "",
        "parentId": 15004572757671,
        "searchType": 5,
        "livePriceParam": {}
    },
    "i18n": {
        "language": "zh",
        "timezone": "8"
    },
    "orderBy": [
        {
            "field": "complex",
            "sort": "desc"
        }
    ],
    "pageNum": 1,
    "pageSize": 10
}

json_data_info = {
    "refer": "ec-goods-detail",
    "extendParameter": {
        "sceneId": "",
        "sceneType": "",
        "tsoTicket": "",
        "wmkTicket": ""
    },
    "basicInfo": {
        "vid": 6001545981671,
        "vidType": 2,
        "bosId": 4001924227671,
        "productId": 145,
        "productInstanceId": 3273861671,
        "productVersionId": "12010",
        "merchantId": 2000019450671,
        "cid": 228447671,
        "tcode": "weimob"
    },
    "extendInfo": {
        "source": 2,
        "youshu": {
            "token": "tokenStr",
            "enable": True
        },
        "refer": "ec-goods-detail",
        "deviceInfo": {
            "osType": 2
        },
        "channelsource": 5
    },
    "templateId": 20,
    "queryParameter": {
        "livePriceParam": {
            "livePriceId": "",
            "livePriceType": ""
        },
        "goodsId": 125778180757671,
        "bizCode": "",
        "activityId": "",
        "activityType": "",
        "extParameter": {}
    },
    "i18n": {
        "language": "zh",
        "timezone": "8"
    },
    "bizVid": 6001545981671
}


def getGoodsList(pageNum=1, pageSize=10):
    json_data["pageNum"] = pageNum
    json_data["pageSize"] = pageSize
    print('POST', f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/getGoodsList')
    response = requests.post(
        f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/getGoodsList',
        cookies=cookies,
        json=json_data,
    )
    if response.status_code != 200:
        print('getGoodsList error', response.status_code, response.text)
        return None
    else:
        '''
        {
            "errcode": "0",
            "errmsg": "处理成功",
            "data": {
                "title": "春夏新品",
                "recentSearchVidName": null,
                "recentSearchVidId": null,
                "intelligentSort": false,
                "participleEnabled": false,
                "elaborateParticipleEnabled": false,
                "algorithmModel": 0,
                "algSearch": false,
                "paginationData": {
                    "pageNum": 1,
                    "pageSize": 10,
                    "totalCount": 959,
                    "pageList": [
                        {
                            "id": 125778180757671,
                            "availableStockNum": 133,
                            "activityId": null,
                            "activityType": null,
                            "showAddCart": true,
                            "defaultImageUrl": "https://image-c.weimobwmc.com/ol-6LF98/3fc72d48bdf24d999ec8b4962f0f71c9.jpg",
                            "tag": {
                                "goodsBizTag": [],
                                "activityTag": []
                            },
                            "contractTag": null,
                            "title": "T恤｜挺括有型宽松圆领短袖男女童24夏1O5110210",
                            "isMultiSku": 1,
                            "isMemberDiscount": 0,
                            "isDisplayMemberIcon": 0,
                            "saleChannelType": 3,
                            "minMermberShipPrice": null,
                            "maxMermberShipPrice": null,
                            "minOriginalPrice": 365.0000,
                            "minSalePrice": 365.0000,
                            "maxSalePrice": 365.0000,
                            "minActivityPrice": null,
                            "goodsPromotionType": 1,
                            "b2cGoodsType": 0,
                            "goodsBizType": 1,
                            "subGoodsBizType": 101,
                            "recommendType": -1,
                            "goodsSaleNum": 441,
                            "skuJump": 0,
                            "priceDisplayText": null,
                            "url": {
                                "h5Url": "https://228447671.shop.n.weimob.com/bos/shop/228447671/6001545981671/3273861671/goods/detail/index?wid=-17465382675781272&recommendType=-1&bizVid=6001545981671&id=125778180757671",
                                "miniUrl": "/ec_goods/detail?productInstanceId=3273861671&vid=6001545981671&wid=-17465382675781272&recommendType=-1&bizVid=6001545981671&id=125778180757671"
                            },
                            "vid": 6001545981671,
                            "belongVid": 6001545981671,
                            "vidName": null,
                            "vidUrl": null,
                            "vidType": null,
                            "pageId": null,
                            "distributionHint": null,
                            "soldOutLogoDisplayStatus": 1,
                            "isKnowledgePayment": false,
                            "drugGoodsType": null,
                            "sellUnitTitle": null,
                            "recommendMemberPrice": null,
                            "expectedPriceResponse": null,
                            "isExpectPrice": 0,
                            "relatedServiceGroup": false,
                            "specValueInfoList": null,
                            "showVideoTag": false,
                            "showLiveTag": false,
                            "liveTagStyle": 0,
                            "customLiveTagUrl": null
                        }
                    ]
                },
                "wechatShare": {
                    "title": "春夏新品-jnby by JNBY官方商城",
                    "content": "来自好友xx的推荐",
                    "imageUrl": null,
                    "url": null,
                    "shareUrl": {
                        "h5Url": "https://228447671.shop.n.weimob.com/bos/shop/228447671/6001545981671/3273861671/goods/list/index?parentId=12962068757671&id=12962068757671&essharewid=-17465382675781272&recommendTicket=recommend_1_11_62r6y&vid=6001545981671&share_vid=6001545981671&pmc=3%7C5.essharewid.0-1%7C3%7C5.recommendTicket.0-3.vid.0-2%7C3%7C5.share_vid.86400",
                        "miniUrl": "/ec_shop/goods?productInstanceId=3273861671&vid=6001545981671&parentId=12962068757671&id=12962068757671&essharewid=-17465382675781272&recommendTicket=recommend_1_11_62r6y&share_vid=6001545981671&pmc=3%7C5.essharewid.0-1%7C3%7C5.recommendTicket.0-3.vid.0-2%7C3%7C5.share_vid.86400"
                    },
                    "hideShare": false
                },
                "style": {
                    "pageType": 1,
                    "showType": 1,
                    "navigateId": null,
                    "title": "",
                    "description": "",
                    "styleType": 0,
                    "categoryTemplateADStatus": 0,
                    "soldOutSign": 0,
                    "categoryNavigationList": null,
                    "styleExData": {
                        "showGoodsSaleNum": 0,
                        "showGoodsTag": 1,
                        "showCart": 2,
                        "showImage": 1,
                        "imageSize": 2,
                        "topNavBarColorStyle": 1,
                        "backColor": "#FFFFFF",
                        "contentColor": "#000000"
                    },
                    "departmentId": 0,
                    "vid": 6001545981671,
                    "shareImageConfig": 0
                },
                "pageStyleConfig": {
                    "showRecommendMemberPrice": 0,
                    "isExpectPrice": 0,
                    "showSpecificationImage": 0
                }
            },
            "globalTicket": "5803-1746541750.859-saas-w1-1519-37597777371",
            "monitorTrackId": "681a1cb68ce8c81606780e99"
        }
        '''
        return response.json()

def getSkuInfo(goodsId):
    json_data_info["queryParameter"]["goodsId"] = goodsId
    print('POST', f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/v3/skuInfo')
    response = requests.post(
        f'https://{SHOP_ID}.shop.n.weimob.com/api3/mall/navigation/goods/v3/skuInfo',
        cookies=cookies,
        json=json_data_info,
    )
    if response.status_code != 200:
        print('getSkuInfo error', response.status_code, response.text)
        return None
    else:
        '''
        {
            "errcode": "0",
            "errmsg": "处理成功",
            "data": {
                "productId": 145,
                "productInstanceId": 3273861671,
                "drawGoodsInfo": null,
                "commonGoodsTag": null,
                "commonGoodsActivityStatus": null,
                "isCommonGoodsActivityBar": null,
                "goodsImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/3fc72d48bdf24d999ec8b4962f0f71c9.jpg",
                "spuShowStock": 134,
                "isShowStock": true,
                "goodsId": 125778180757671,
                "vid": 6001545981671,
                "vidType": 2,
                "belongVid": 6001545981671,
                "bizCode": null,
                "saleChannelType": 3,
                "isCanSell": 1,
                "isDeleted": false,
                "isPutAway": 0,
                "limitStatus": null,
                "priceNameDes": null,
                "canOriginBuy": null,
                "canBuyNum": null,
                "alreadyBuyGoodsNum": null,
                "settingLimitNum": null,
                "goodsPromotionType": 1,
                "subGoodsPromotionType": null,
                "goodsBizType": 1,
                "b2cGoodsType": 0,
                "showPriceNameDes": null,
                "isMultiSku": 1,
                "isMultiStart": false,
                "skuInfos": [
                    {
                        "attributeId": 123481727171,
                        "name": "颜色",
                        "attrValueList": [
                            {
                                "key": "142251206171",
                                "value": "001/本黑",
                                "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/edf75e60f4924d9eb6ddc99b7c65158d.jpg",
                                "attrImgUrlList": null
                            },
                            {
                                "key": "142251227171",
                                "value": "075/杂中灰",
                                "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/a55aa634c2e3474fbf4055f207f91ae3.jpg",
                                "attrImgUrlList": null
                            },
                            {
                                "key": "144084802171",
                                "value": "272/驼杏色",
                                "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/02862f20b9d14880ae115e17d74e911c.jpg",
                                "attrImgUrlList": null
                            },
                            {
                                "key": "28015306757671",
                                "value": "272/驼杏色（批次1）",
                                "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/26a7cb1ade3d41d7b0ec051fd7f231ae.jpg",
                                "attrImgUrlList": null
                            },
                            {
                                "key": "25617679757671",
                                "value": "001/本黑（批次1）",
                                "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/ca6310f8803c4dec98d716745ce1b506.jpg",
                                "attrImgUrlList": null
                            },
                            {
                                "key": "25618163757671",
                                "value": "075/杂中灰（批次1）",
                                "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/a3b5a9a1b1b34e26955cf4e126d75f62.jpg",
                                "attrImgUrlList": null
                            },
                            {
                                "key": "32478712757671",
                                "value": "272/驼杏色（批次2）",
                                "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/87cbf5cb6d8e4a25b122eb67d7fddc90.jpg",
                                "attrImgUrlList": null
                            }
                        ],
                        "attrImgUrl": null,
                        "attrImgEnable": true
                    },
                    {
                        "attributeId": 123507271171,
                        "name": "尺码",
                        "attrValueList": [
                            {
                                "key": "141852957171",
                                "value": "100cm",
                                "attrImgUrl": null,
                                "attrImgUrlList": null
                            },
                            {
                                "key": "141839698171",
                                "value": "110cm",
                                "attrImgUrl": null,
                                "attrImgUrlList": null
                            },
                            {
                                "key": "141851541171",
                                "value": "120cm",
                                "attrImgUrl": null,
                                "attrImgUrlList": null
                            },
                            {
                                "key": "141839699171",
                                "value": "130cm",
                                "attrImgUrl": null,
                                "attrImgUrlList": null
                            },
                            {
                                "key": "141838976171",
                                "value": "140cm",
                                "attrImgUrl": null,
                                "attrImgUrlList": null
                            },
                            {
                                "key": "141838369171",
                                "value": "150cm",
                                "attrImgUrl": null,
                                "attrImgUrlList": null
                            },
                            {
                                "key": "141847702171",
                                "value": "160cm",
                                "attrImgUrl": null,
                                "attrImgUrlList": null
                            }
                        ],
                        "attrImgUrl": null,
                        "attrImgEnable": false
                    }
                ],
                "skuNames": [
                    "颜色",
                    "尺码"
                ],
                "skuValueVos": [
                    {
                        "id": 208423271757671,
                        "imageUrl": "https://image-c.weimobwmc.com/ol-6LF98/edf75e60f4924d9eb6ddc99b7c65158d.jpg",
                        "skuInfoMap": {
                            "123507271171": 141852957171,
                            "123481727171": 142251206171
                        },
                        "activitySku": false,
                        "skuPrices": {
                            "memberPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "minSpuPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "maxMemberPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "defaultSkuId": {
                                "priceName": "208423271757671",
                                "value": ""
                            },
                            "minMemberPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "maxDeletePrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "point": {
                                "priceName": null,
                                "value": ""
                            },
                            "deletePrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "maxSpuPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "showPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "spuPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "minDeletePrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "memberDiscountPrice": {
                                "priceName": "",
                                "value": ""
                            },
                            "buttonPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "depositPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "spuDeletePrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "skuId": {
                                "priceName": "208423271757671",
                                "value": ""
                            }
                        },
                        "selectNum": null,
                        "availableStockNum": 23,
                        "stockNum": null,
                        "button": {
                            "type": 18,
                            "enable": 1,
                            "text": "确认"
                        },
                        "isDisabled": false,
                        "purchaseCodeType": false,
                        "purchaseActivityId": null,
                        "purchaseActivityTypeId": null,
                        "stockAvailableNoticeType": 0,
                        "pointSkuInfo": null,
                        "activityPrice": null,
                        "cycleSkuInfo": null
                    },
                    {
                        "id": 208423272757671,
                        "imageUrl": "https://image-c.weimobwmc.com/ol-6LF98/edf75e60f4924d9eb6ddc99b7c65158d.jpg",
                        "skuInfoMap": {
                            "123507271171": 141839698171,
                            "123481727171": 142251206171
                        },
                        "activitySku": false,
                        "skuPrices": {
                            "deletePrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "showPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "memberPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "spuPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "buttonPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "depositPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "spuDeletePrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "point": {
                                "priceName": null,
                                "value": ""
                            },
                            "skuId": {
                                "priceName": "208423272757671",
                                "value": ""
                            }
                        },
                        "selectNum": null,
                        "availableStockNum": 51,
                        "stockNum": null,
                        "button": {
                            "type": 18,
                            "enable": 1,
                            "text": "确认"
                        },
                        "isDisabled": false,
                        "purchaseCodeType": false,
                        "purchaseActivityId": null,
                        "purchaseActivityTypeId": null,
                        "stockAvailableNoticeType": 0,
                        "pointSkuInfo": null,
                        "activityPrice": null,
                        "cycleSkuInfo": null
                    },
                    {
                        "id": 208423273757671,
                        "imageUrl": "https://image-c.weimobwmc.com/ol-6LF98/edf75e60f4924d9eb6ddc99b7c65158d.jpg",
                        "skuInfoMap": {
                            "123507271171": 141851541171,
                            "123481727171": 142251206171
                        },
                        "activitySku": false,
                        "skuPrices": {
                            "deletePrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "showPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "memberPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "spuPrice": {
                                "priceName": null,
                                "value": 365.0000
                            },
                            "buttonPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "depositPrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "spuDeletePrice": {
                                "priceName": null,
                                "value": ""
                            },
                            "point": {
                                "priceName": null,
                                "value": ""
                            },
                            "skuId": {
                                "priceName": "208423273757671",
                                "value": ""
                            }
                        },
                        "selectNum": null,
                        "availableStockNum": 30,
                        "stockNum": null,
                        "button": {
                            "type": 18,
                            "enable": 1,
                            "text": "确认"
                        },
                        "isDisabled": false,
                        "purchaseCodeType": false,
                        "purchaseActivityId": null,
                        "purchaseActivityTypeId": null,
                        "stockAvailableNoticeType": 0,
                        "pointSkuInfo": null,
                        "activityPrice": null,
                        "cycleSkuInfo": null
                    }
                ],
                "prices": {
                    "memberPrice": {
                        "priceName": null,
                        "value": ""
                    },
                    "minSpuPrice": {
                        "priceName": null,
                        "value": 365.0000
                    },
                    "maxMemberPrice": {
                        "priceName": null,
                        "value": ""
                    },
                    "defaultSkuId": {
                        "priceName": "208423271757671",
                        "value": ""
                    },
                    "minMemberPrice": {
                        "priceName": null,
                        "value": ""
                    },
                    "maxDeletePrice": {
                        "priceName": null,
                        "value": 365.0000
                    },
                    "point": {
                        "priceName": null,
                        "value": ""
                    },
                    "deletePrice": {
                        "priceName": null,
                        "value": ""
                    },
                    "maxSpuPrice": {
                        "priceName": null,
                        "value": 365.0000
                    },
                    "showPrice": {
                        "priceName": null,
                        "value": 365.0000
                    },
                    "spuPrice": {
                        "priceName": null,
                        "value": 365.0000
                    },
                    "minDeletePrice": {
                        "priceName": null,
                        "value": 365.0000
                    },
                    "memberDiscountPrice": {
                        "priceName": "",
                        "value": ""
                    },
                    "buttonPrice": {
                        "priceName": null,
                        "value": ""
                    },
                    "depositPrice": {
                        "priceName": null,
                        "value": ""
                    },
                    "spuDeletePrice": {
                        "priceName": null,
                        "value": ""
                    },
                    "skuId": {
                        "priceName": "208423271757671",
                        "value": ""
                    }
                },
                "goodsButtonList": [
                    {
                        "type": 1,
                        "enable": 1,
                        "text": "加入购物车"
                    },
                    {
                        "type": 2,
                        "enable": 1,
                        "text": "立即购买"
                    }
                ],
                "scheduleSellInfo": null,
                "preSellGoodsInfo": null,
                "goodsStatus": 1,
                "goodsSaleMsg": null,
                "saleButtonMsg": null,
                "saleButtonType": null,
                "skuSaleTip": null,
                "cycleGoods": null,
                "pointGoodsInfo": null,
                "activityId": null,
                "activityType": null,
                "subActivityType": null,
                "activityStatus": null,
                "activityStock": null,
                "activityTag": null,
                "activityDesc": null,
                "promotionOverlay": null,
                "itemType": null,
                "itemList": null,
                "remindSwitch": null,
                "userAttention": null,
                "remindBarText": null,
                "remindButtonSwitch": null,
                "alreadySetRemind": null,
                "remindType": null,
                "lowestPriceDay": null,
                "reserveStatus": null,
                "deliveryTypeList": null,
                "activityDoc": null,
                "timeDisplayConfig": null,
                "countDownInfo": null,
                "progressBarList": null,
                "progressBar": null,
                "grouponRecommendList": null,
                "grouponNumber": null,
                "totalPeopleAmount": null,
                "grouponType": null,
                "subscribeNum": null,
                "selectPeople": null,
                "grouponTag": null,
                "goodsLimitSwitch": 0,
                "goodsLimitNum": null,
                "settingGoodsLimitNum": null,
                "singleOrderCanBuyNum": "",
                "limitPeriodRule": null,
                "limitPeriodRuleName": null,
                "addCartType": 0,
                "isAssignStore": 1,
                "authentication": null,
                "fenQiPayment": true,
                "isExpectPrice": 1,
                "showExpectButton": true,
                "expectedPriceResponse": null,
                "limitPromotionType": null,
                "originButtonList": [
                    {
                        "type": 1,
                        "enable": 1,
                        "text": "加入购物车"
                    },
                    {
                        "type": 2,
                        "enable": 1,
                        "text": "立即购买"
                    }
                ],
                "needNum": null,
                "supportNum": null,
                "goodsClassifyIdList": [
                    13007158757671,
                    13888569757671,
                    121818714271,
                    12898276757671,
                    13196907757671,
                    13916217757671,
                    12891501757671,
                    13196718757671,
                    11782187757671,
                    121809694271
                ],
                "itemClassifyId": null,
                "categoryId": 60,
                "categoryTree": {
                    "categoryId": 5,
                    "categoryName": "母婴",
                    "parentCategoryId": 0,
                    "categoryLevel": 1,
                    "isLeaf": false,
                    "isValid": null,
                    "categoryGroup": null,
                    "categoryCertificateDTO": null,
                    "categoryPropertyList": null,
                    "childrenCategory": {
                        "categoryId": 60,
                        "categoryName": "童装童鞋",
                        "parentCategoryId": 5,
                        "categoryLevel": 2,
                        "isLeaf": true,
                        "isValid": null,
                        "categoryGroup": null,
                        "categoryCertificateDTO": null,
                        "categoryPropertyList": null,
                        "childrenCategory": null
                    }
                },
                "param": null,
                "goodsAttrInfo": null,
                "sellUnitTitle": null,
                "channelPriceStatus": null,
                "channelCode": null,
                "purchaseCode": null,
                "alipayByStages": null,
                "freeFeeNums": null,
                "sizeTable": null,
                "showRangePrice": false,
                "liveFloatingWindowSwitch": true,
                "recommendSite": 2,
                "promotionStyle": 1,
                "showDeletedPrice": 1,
                "placeOrderWay": 0,
                "popularizeText": null,
                "showStoreHead": 1,
                "title": "T恤｜挺括有型宽松圆领短袖男女童24夏1O5110210",
                "showSpecImg": 1,
                "specImgInfoList": [
                    {
                        "attrId": null,
                        "attrValueId": null,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/3fc72d48bdf24d999ec8b4962f0f71c9.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": false,
                        "attrShowText": null,
                        "skuId": null
                    },
                    {
                        "attrId": 123481727171,
                        "attrValueId": 142251206171,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/edf75e60f4924d9eb6ddc99b7c65158d.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": false,
                        "attrShowText": "001/本黑",
                        "skuId": null
                    },
                    {
                        "attrId": 123481727171,
                        "attrValueId": 142251227171,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/a55aa634c2e3474fbf4055f207f91ae3.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": true,
                        "attrShowText": "075/杂中灰(已售罄)",
                        "skuId": null
                    },
                    {
                        "attrId": 123481727171,
                        "attrValueId": 144084802171,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/02862f20b9d14880ae115e17d74e911c.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": false,
                        "attrShowText": "272/驼杏色",
                        "skuId": null
                    },
                    {
                        "attrId": 123481727171,
                        "attrValueId": 28015306757671,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/26a7cb1ade3d41d7b0ec051fd7f231ae.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": true,
                        "attrShowText": "272/驼杏色（批次1）(已售罄)",
                        "skuId": null
                    },
                    {
                        "attrId": 123481727171,
                        "attrValueId": 25617679757671,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/ca6310f8803c4dec98d716745ce1b506.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": true,
                        "attrShowText": "001/本黑（批次1）(已售罄)",
                        "skuId": null
                    },
                    {
                        "attrId": 123481727171,
                        "attrValueId": 25618163757671,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/a3b5a9a1b1b34e26955cf4e126d75f62.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": true,
                        "attrShowText": "075/杂中灰（批次1）(已售罄)",
                        "skuId": null
                    },
                    {
                        "attrId": 123481727171,
                        "attrValueId": 32478712757671,
                        "attrImgUrl": "https://image-c.weimobwmc.com/ol-6LF98/87cbf5cb6d8e4a25b122eb67d7fddc90.jpg",
                        "attrImgUrlList": null,
                        "emptyStock": true,
                        "attrShowText": "272/驼杏色（批次2）(已售罄)",
                        "skuId": null
                    }
                ],
                "extendTips": null,
                "originalBuy": null,
                "activityGoodsLimit": null,
                "applicablePeopleButtonUrl": null,
                "serviceGroupList": [],
                "receiveAddress": null,
                "showWechatLive": null,
                "showWeimobLive": null,
                "showPreDelivery": false,
                "hasSingleMemberOverlay": null,
                "needQuerySingleMemberOverlay": null,
                "mallVersionType": null
            },
            "globalTicket": "2301-1746540244.333-saas-w1-1557-37593062083",
            "monitorTrackId": "681a16d40f22db30921005b2"
        }
        '''
        return response.json()

def get_product_code(title):
    # 提取商品标题中的商品编码
    pattern = r'([A-Za-z\d]{6,11})'
    match = re.search(pattern, title)
    return match.group(0) if match else ''

def sleep_random():
    random_value = random.uniform(0.5, 1.0)
    print(f"等待{random_value:.2f}s ...")
    time.sleep(random_value)

if __name__ == '__main__':
    goods_list = getGoodsList()
    if goods_list and goods_list.get('errcode') == '0':
        # 获取商品列表个数
        total_count = goods_list['data']['paginationData']['totalCount']
        # 计算需要获取的总页数，每页50个商品
        total_pages = (total_count + 49) // 50  # 向上取整

        sleep_random()

        # 获取已添加的商品货号
        # skip_codes = []
        skip_codes = get_records_goods_no_list()
        print(f"已添加的商品货号: {skip_codes.count()}个")

        # 获取剩余商品列表，pageSize不超过50
        for pageNum in range(1, total_pages + 1):
        # for pageNum in range(1, 2):
            records = []
            goods_list = getGoodsList(pageNum=pageNum, pageSize=50)
            sleep_random()

            if goods_list and goods_list['errcode'] == '0':
                goods_data = goods_list['data']['paginationData']['pageList']
                for goods in goods_data:
                    goods_id = goods['id']
                    # 根据商品ID判断是否已添加
                    # if is_goods_added(goods_id):
                    #     print(f"商品ID: {goods_id} 已添加")
                    #     continue

                    print(f"商品ID: {goods_id}")

                    sku_info = getSkuInfo(goods_id)
                    sku_info_data = sku_info['data']
                    if not sku_info_data:
                        print(f"获取商品详情失败, 商品ID: {goods_id}, {sku_info.get('errmsg')}")
                        exit()
                    title = sku_info_data['title'].replace('｜', '-')
                    sleep_random()
                    if '24' in title:
                        # 跳过24年的商品
                        # print(f"跳过24年商品: {title}")
                        continue

                    if '25秋' not in title and '25冬' not in title:
                        # 筛选25秋的商品
                        # print(f"筛选25秋商品: {title}")
                        continue

                    product_code = get_product_code(title)
                    if product_code in skip_codes:
                        # print(f"跳过指定货号商品: {product_code}")
                        continue
                    origin_price = sku_info_data['prices']['maxDeletePrice']['value'] or sku_info_data['prices']['maxSpuPrice']['value'] or sku_info_data['prices']['showPrice']['value']
                    category = sku_info_data['categoryTree']['categoryName'] + '/' + sku_info_data['categoryTree']['childrenCategory']['categoryName']
                    goodsImgUrl = sku_info_data['goodsImgUrl']
                    # spec_map_for_create = {row['spec1_name']:[row['spec1_value']],row['spec2_name']:good_ruler_2_value_list}
                    skuInfos = sku_info_data['skuInfos']
                    specs = []
                    specs_images = []
                    if len(skuInfos) > 1:
                        for attr in skuInfos:
                            attr_name = attr['name']
                            attr_values = [value['value'] for value in attr['attrValueList'] 
                                        if not '批次' in value['value']]
                            specs.append({
                                "name": attr_name,
                                "values": attr_values
                            })
                            
                            # 如果是颜色属性，则构建颜色与图片的映射
                            if attr['attrImgEnable']:
                                specs_images.extend([
                                    {
                                        "type": value['value'],
                                        "image_url": value['attrImgUrl'],
                                        # "file_path": file_path,
                                        # "file_token": file_token,
                                    }
                                    for value in attr['attrValueList'] 
                                    if (value['attrImgUrl'] and 
                                        not '批次' in value['value'])
                                    # for file_path in [download_image(value['attrImgUrl'])]
                                    # if file_path
                                    # for file_token in [upload_media(file_path)]
                                    # if file_token
                                ])
                    else:
                        print("商品规格不满足要求", skuInfos)

                    print(f"商品ID: {goods_id}, 标题: {title}, 货号：{product_code}, 原价: {origin_price}, 分类: {category}, 图片: {goodsImgUrl}", specs, specs_images)

                    file_path = download_image(goodsImgUrl)
                    file_token = upload_media(file_path)

                    records.append({
                        "fields": {
                            "货号": product_code,
                            "商品ID": str(goods_id),
                            "商品名称": title,
                            "划线价(元)": origin_price,
                            "分类": category,
                            "商品图片": [{"file_token": file_token}],
                            "商品图片链接": {
                                "link": goodsImgUrl,
                                "text": goodsImgUrl
                            },
                            # "商品图片本地路径": file_path,
                            "商品规格1-名称": specs[0]['name'] if len(specs) > 0 else None,
                            "商品规格1-值": ",".join(specs[0]['values']) if len(specs) > 0 and specs[0]['values'] else None,
                            # "商品规格1-图片": [{"file_token": v["file_token"]} for v in specs_images if v["file_token"]],
                            "商品规格1-图片链接": ",".join([v["image_url"] for v in specs_images if v["image_url"]]),
                            # "商品规格1-图片本地路径": ",".join([v["file_path"] for v in specs_images if v["file_path"]]),
                            "商品规格2-名称": specs[1]['name'] if len(specs) > 1 else None,
                            "商品规格2-值": ",".join(specs[1]['values']) if len(specs) > 1 and specs[1]['values'] else None,
                        }
                    })
                    
            if records and len(records) > 0:
                print(f"新增 {len(records)} 商品记录...")
                # 每次最多上传1000条
                batch_size = 1000
                for i in range(0, len(records), batch_size):
                    batch_records = records[i:i + batch_size]
                    if batch_create_records(batch_records):
                        print(f"新增商品记录 {len(batch_records)} 条成功")
                    else:
                        print("新增商品记录失败")
            else:
                print("没有需要新增的商品记录")

    else:
        print("获取商品列表失败", goods_list)
        
    input("按任意键退出...")
